﻿using AutoMapper;
using IOA.MES.Common;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using IOA.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IOA.MES.Business
{
    /// <summary>
    /// 不良原因配置（错误代码：131001）
    /// </summary>
    public class BadReasonMgr
    {
        private MESContext mesDb = new MESContext("MES");

        /// <summary>
        /// 编辑
        /// </summary>
        public VBadReason EditReason(VBadReason model)
        {
            if (model.PkId <= 0)
            {
                var type = mesDb.BadTypes.AsNoTracking().FirstOrDefault(_ => _.TypeCode == model.BadTypeCode && _.Valid);
                if (type == null)
                {
                    throw new MultiLanBizException(131005);//当前分类不存在
                }
                var exist = mesDb.BadReasons.AsNoTracking().FirstOrDefault(_ => _.ReasonCode == model.ReasonCode && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(131006, model.ReasonCode);//异常代码已存在
                }
                model.CreateTime = DateTime.Now;
                var entity = Mapper.Map<BadReason>(model);
                mesDb.BadReasons.Add(entity);

                if (entity.KeyIndex.HasValue)
                {
                    var otherKeys = mesDb.BadReasons.AsNoTracking().Where(_ => _.KeyIndex == model.KeyIndex.Value && _.Valid).ToList();
                    otherKeys.ForEach(_ =>
                    {
                        mesDb.BadReasons.Attach(_);
                        _.KeyIndex = null;
                        _.ModifyBy = entity.CreateBy;
                        _.ModifyTime = DateTime.Now;
                    });
                }
                mesDb.SaveChanges();

                model = Mapper.Map<VBadReason>(entity);
            }
            else
            {
                var entity = mesDb.BadReasons.AsNoTracking().FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
                if (entity == null)
                {
                    throw new MultiLanBizException(131001);// "待编辑的记录不存在或已被删除，无法编辑");
                }
                var type = mesDb.BadTypes.AsNoTracking().FirstOrDefault(_ => _.TypeCode == model.BadTypeCode && _.Valid);
                if (type == null)
                {
                    throw new MultiLanBizException(131005);//当前分类不存在
                }
                var exist = mesDb.BadReasons.AsNoTracking().FirstOrDefault(_ => _.PkId != model.PkId && _.ReasonCode == model.ReasonCode && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(131006, model.ReasonCode);//异常代码已存在
                }

                mesDb.BadReasons.Attach(entity);
                entity.KeyIndex = model.KeyIndex;
                entity.BadTypeCode = model.BadTypeCode;
                entity.IsMaterielBad = model.IsMaterielBad;
                entity.ReasonCN = model.ReasonCN;
                entity.ReasonVN = model.ReasonVN;
                entity.ReasonEN = model.ReasonEN;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;

                if (entity.KeyIndex.HasValue)
                {
                    var otherKeys = mesDb.BadReasons.AsNoTracking().Where(_ => _.PkId != entity.PkId && _.KeyIndex == model.KeyIndex.Value && _.Valid).ToList();
                    otherKeys.ForEach(_ =>
                    {
                        mesDb.BadReasons.Attach(_);
                        _.KeyIndex = null;
                        _.ModifyBy = entity.CreateBy;
                        _.ModifyTime = DateTime.Now;
                    });
                }
                mesDb.SaveChanges();

                model = Mapper.Map<VBadReason>(entity);
            }
            return model;
        }

        /// <summary>
        /// 查询
        /// </summary>
        public VBadReason GetReason(int pkId, string badCode = "")
        {
            var entity = pkId > 0 ? mesDb.BadReasons.AsNoTracking().FirstOrDefault(_ => _.PkId == pkId && _.Valid)
                : mesDb.BadReasons.AsNoTracking().FirstOrDefault(_ => _.ReasonCode == badCode && _.Valid);

            if (entity == null)
            {
                return null;
            }
            var model = Mapper.Map<VBadReason>(entity);
            var type = mesDb.BadTypes.AsNoTracking().FirstOrDefault(_ => _.TypeCode == model.BadTypeCode);
            model.BadTypeCode = type?.TypeCode;
            model.BadTypeName = type?.TypeName;
            return model;
        }

        /// <summary>
        /// 查询异常列表
        /// </summary>
        public List<VBadReason> QueryReasons(List<string> badCodes)
        {
            var query = from badReason in mesDb.BadReasons.AsNoTracking()
                        join badType in mesDb.BadTypes.AsNoTracking() on badReason.BadTypeCode equals badType.TypeCode
                        where badReason.Valid && badCodes.Contains(badReason.ReasonCode) && badType.Valid
                        select new VBadReason
                        {
                            PkId = badReason.PkId,
                            ReasonType = badReason.ReasonType,
                            BadTypeCode = badReason.BadTypeCode,
                            BadTypeName = badType.TypeName,
                            ReasonCode = badReason.ReasonCode,
                            ReasonCN = badReason.ReasonCN,
                            ReasonVN = badReason.ReasonVN,
                            ReasonEN = badReason.ReasonEN,
                            Valid = badReason.Valid,
                            CreateBy = badReason.CreateBy,
                            CreateTime = badReason.CreateTime,
                            ModifyBy = badReason.ModifyBy,
                            ModifyTime = badReason.ModifyTime
                        };

            var entities = query.OrderBy(_ => _.BadTypeCode).ThenBy(_ => _.ReasonCode).ToList();

            return Mapper.Map<List<VBadReason>>(entities);
        }

        /// <summary>
        /// 搜索
        /// </summary>
        public List<VBadReason> QueryReasons(int pageIndex, int pageSize, out int total, string type, string reason)
        {
            var query = from badReason in mesDb.BadReasons.AsNoTracking()
                        join badType in mesDb.BadTypes.AsNoTracking() on badReason.BadTypeCode equals badType.TypeCode
                        where badReason.Valid && badType.Valid
                        select new VBadReason
                        {
                            PkId = badReason.PkId,
                            ReasonType = badReason.ReasonType,
                            BadTypeCode = badReason.BadTypeCode,
                            BadTypeName = badType.TypeName,
                            ReasonCode = badReason.ReasonCode,
                            IsMaterielBad = badReason.IsMaterielBad,
                            ReasonCN = badReason.ReasonCN,
                            ReasonVN = badReason.ReasonVN,
                            ReasonEN = badReason.ReasonEN,
                            Valid = badReason.Valid,
                            CreateBy = badReason.CreateBy,
                            CreateTime = badReason.CreateTime,
                            ModifyBy = badReason.ModifyBy,
                            ModifyTime = badReason.ModifyTime
                        };
            if (!string.IsNullOrWhiteSpace(reason))
            {
                query = query.Where(_ => _.ReasonCode.Contains(reason) || _.ReasonCN.Contains(reason) || _.ReasonVN.Contains(reason) || _.ReasonEN.Contains(reason));
            }
            if (!string.IsNullOrWhiteSpace(type))
            {
                query = query.Where(_ => _.BadTypeCode.Contains(type) || _.BadTypeName.Contains(type));
            }

            total = query.Count();
            query = query.OrderBy(_ => _.BadTypeCode).ThenBy(_ => _.ReasonCode);
            var entities = pageSize <= 0 ? query.ToList() : query.Skip((pageIndex - 1) * pageSize).Take(pageSize).OrderByDescending(_ => _.PkId).ToList();

            return Mapper.Map<List<VBadReason>>(entities);
        }

        /// <summary>
        /// 查询异常列表
        /// </summary>
        /// <param name="reasonType">异常类别</param>
        /// <returns>异常列表</returns>
        public List<VBadReason> QueryReasons(JudgeType reasonType)
        {
            var entities = mesDb.BadReasons.Where(_ => (_.ReasonType.HasValue == false || _.ReasonType == reasonType) && _.Valid)
                .OrderBy(_ => _.BadTypeCode).ThenBy(_ => _.ReasonCode).ToList();
            return Mapper.Map<List<VBadReason>>(entities);
        }

        /// <summary>
        /// 删除
        /// </summary>
        public void DeleteReason(VBadReason model)
        {
            var entity = mesDb.BadReasons.FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
            if (entity == null)
            {
                throw new MultiLanBizException(131002);// "数据不存在或已被删除，无法重复删除");
            }
            entity.Valid = false;
            entity.ModifyBy = model.ModifyBy;
            entity.ModifyTime = DateTime.Now;
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 查询不良大类列表
        /// </summary>
        /// <param name="page">页面索引</param>
        /// <param name="limit">页面容量</param>
        /// <param name="total">全部数量</param>
        /// <param name="key">分类代码/名称</param>
        /// <returns>列表</returns>
        public List<VBadType> QueryTypes(int page, int limit, out int total, string key)
        {
            var query = mesDb.BadTypes.AsNoTracking().Where(_ => _.Valid);
            if (!string.IsNullOrWhiteSpace(key))
            {
                query = query.Where(_ => _.TypeCode.Contains(key) || _.TypeName.Contains(key));
            }

            total = query.Count();
            query = query.OrderBy(_ => _.SortNo);
            var entities = limit <= 0 ? query.ToList() : query.Skip((page - 1) * limit).Take(limit).ToList();

            return Mapper.Map<List<VBadType>>(entities);
        }

        /// <summary>
        /// 获取异常大类
        /// </summary>
        /// <param name="pkId">主键</param>
        /// <returns>大类</returns>
        public VBadType GetBadType(int pkId)
        {
            return Mapper.Map<VBadType>(mesDb.BadTypes.AsNoTracking().FirstOrDefault(_ => _.PkId == pkId && _.Valid));
        }

        /// <summary>
        /// 编辑大类
        /// </summary>
        /// <param name="model">分类对象</param>
        public void EditType(VBadType model)
        {
            if (model.PkId <= 0)
            {
                var exist = mesDb.BadTypes.AsNoTracking().FirstOrDefault(_ => (_.TypeCode == model.TypeCode || _.TypeName == model.TypeName) && _.Valid);
                if (exist != null)
                {
                    if (StringUtils.Equals(exist.TypeCode, model.TypeCode))
                    {
                        throw new MultiLanBizException(131003, model.TypeCode);//分类代码已存在
                    }
                    else
                    {
                        throw new MultiLanBizException(131004, model.TypeName);//分类名称已存在
                    }
                }

                model.CreateTime = DateTime.Now;
                var entity = Mapper.Map<BadType>(model);
                mesDb.BadTypes.Add(entity);
                mesDb.SaveChanges();
            }
            else
            {
                var entity = mesDb.BadTypes.AsNoTracking().FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
                if (entity == null)
                {
                    throw new MultiLanBizException(131005);//当前分类不存在
                }
                var exist = mesDb.BadTypes.AsNoTracking().FirstOrDefault(_ => _.PkId != model.PkId && (_.TypeCode == model.TypeCode || _.TypeName == model.TypeName) && _.Valid);
                if (exist != null)
                {
                    if (StringUtils.Equals(exist.TypeCode, model.TypeCode))
                    {
                        throw new MultiLanBizException(131003, model.TypeCode);//分类代码已存在
                    }
                    else
                    {
                        throw new MultiLanBizException(131004, model.TypeName);//分类名称已存在
                    }
                }

                mesDb.BadTypes.Attach(entity);
                entity.TypeName = model.TypeName;
                entity.SortNo = model.SortNo;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;

                mesDb.SaveChanges();
            }
        }

        /// <summary>
        /// 删除错误分类
        /// </summary>
        /// <param name="model"></param>
        public void DeleteType(VBadType model)
        {
            var entity = mesDb.BadTypes.AsNoTracking().FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
            if (entity != null)
            {
                mesDb.BadTypes.Attach(entity);
                entity.Valid = false;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
                mesDb.SaveChanges();
            }
        }
    }
}
